<template>
  <div class="login-container">
    <h2>登录</h2>
    <div v-if="errorMessage" class="error-message">
      {{ errorMessage }}
    </div>
    <form @submit.prevent="handleLogin" class="login-form">
      <div class="form-group">
        <label>用户名：</label>
        <input type="text" v-model="username" required>
      </div>
      <div class="form-group">
        <label>密码：</label>
        <input type="password" v-model="password" required>
      </div>
      <button type="submit">登录</button>
    </form>
  </div>
</template>

<script>
import router, { asyncRoutes, resetRouter } from '../router'

const users = {
  admin: {
    password: '123',
    role: 'admin'
  },
  student: {
    password: '123',
    role: 'student'
  }
}

export default {
  name: 'LoginView',
  data() {
    return {
      username: '',
      password: '',
      errorMessage: ''
    }
  },
  methods: {
    async handleLogin() {
      try {
        // 检查用户是否存在
        const user = users[this.username]
        if (!user) {
          this.errorMessage = '用户名不存在'
          return
        }

        // 验证密码
        if (user.password !== this.password) {
          this.errorMessage = '密码错误'
          return
        }

        // 清除错误信息
        this.errorMessage = ''
        
        // 重置路由
        resetRouter()
        
        // 存储登录状态和用户角色
        localStorage.setItem('isAuthenticated', 'true')
        localStorage.setItem('userRole', user.role)
        
        // 添加路由
        router.addRoutes(asyncRoutes)
        
        // 等待路由添加完成后再跳转
        await this.$nextTick()
        
        // 如果当前已经在首页，就不需要再跳转
        if (this.$route.path !== '/') {
          await this.$router.push('/')
        }
      } catch (err) {
        if (err.name !== 'NavigationDuplicated') {
          console.error('Navigation error:', err)
        }
      }
    }
  }
}
</script>

<style scoped>
.login-container {
  max-width: 400px;
  margin: 50px auto;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 8px;
  background-color: white;
}

.login-form {
  margin-top: 20px;
}

.form-group {
  margin-bottom: 15px;
}

label {
  display: block;
  margin-bottom: 5px;
}

input {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

button {
  width: 100%;
  padding: 10px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-bottom: 20px;
}

button:hover {
  background-color: #3aa876;
}

.error-message {
  color: #dc3545;
  margin-bottom: 15px;
  padding: 10px;
  background-color: #f8d7da;
  border: 1px solid #f5c6cb;
  border-radius: 4px;
}

.login-tips {
  margin-top: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.login-tips p {
  margin: 5px 0;
  color: #666;
}

.login-tips p:first-child {
  font-weight: bold;
  color: #2c3e50;
}
</style> 